package manager

/*
   服务数据库操作层
*/
import (
	"hermestrans/internal/portal/common"
	config "hermestrans/internal/portal/config"
	"hermestrans/internal/portal/schema"

	"hermestrans/internal/dataccess"

	"github.com/pkg/errors"
	"go.mongodb.org/mongo-driver/bson"
)

type MgoMgr struct {
	*dataccess.Mgo
}

func InitMgoManager(conf *config.Config) (*MgoMgr, error) {
	var (
		err error
		mgo *dataccess.Mgo
	)

	mgo, err = dataccess.NewMgo(conf.MongoConfig.MongodbUri, conf.MongoConfig.MongodbName,
		conf.MongoConfig.MongodbConnectionTimeout, conf.MongoConfig.MaxPoolSize)
	if err != nil {
		return nil, errors.WithMessage(err, "init mongo db fail")
	}
	taskInfoMgo := &MgoMgr{
		mgo,
	}

	return taskInfoMgo, err
}

func (d *MgoMgr) EditJobs(jobs []*schema.Job) error {
	//
	var (
		err           error
		filterUpdates []dataccess.FilterUpdate
	)
	for _, job := range jobs {
		data, err := bson.Marshal(job)
		if err != nil {
			return errors.WithMessage(err, "bson marshal fail")
		}
		filterUpdates = append(filterUpdates, dataccess.FilterUpdate{
			Filter: bson.D{{Key: common.Code, Value: job.Code},
				{Key: common.Name, Value: job.Name},
				{Key: common.JobType, Value: job.JobType},
				{Key: common.Status, Value: job.Status},
				{Key: common.SrcNodeId, Value: job.SrcNodeId},
				{Key: common.SrcNodeName, Value: job.SrcNodeName},
				{Key: common.DestNodeName, Value: job.DestNodeName}},

			Update: bson.D{{Key: "$set", Value: data}},
		})
	}

	if _, err = d.BulkWrite(common.MONGO_COLLECTION_JOBS, filterUpdates); err != nil {
		return errors.WithMessage(err, "jobs bulk write err")
	}
	return nil
}
